package com.gsk.europepharma.salesReport.struts.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Query;
import org.hibernate.Session;

import com.gsk.europepharma.salesReport.hibernate.dao.tbSpBoSRSectoDAO;
import com.gsk.europepharma.salesReport.utils.ColorRenderer;
import com.gsk.europepharma.salesReport.utils.UtilsSalesReport;

/**
 * Gestion des donnees pour l arbre de navigation des differents niveaux.
 */
public class DataSecto extends Action {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// Variables de session
		HttpSession sessionObject = request.getSession();
		Integer cs_adm_pdt = (Integer) sessionObject.getAttribute("cs_adm_pdt");
		Integer cs_adm_rgpt = (Integer) sessionObject.getAttribute("cs_adm_rgpt");
		Integer cs_adm_prstn = (Integer) sessionObject.getAttribute("cs_adm_prstn");
		Integer cs_network = (Integer) sessionObject.getAttribute("cs_network");
		Integer cs_month = (Integer) sessionObject.getAttribute("cs_month");
		// Fin de session 
		
		String source = request.getParameter("source");
		Integer CS_SRC = Integer.parseInt(source);
		String unite = request.getParameter("unite");
		String periode = request.getParameter("periode");
				
		TreeMap<String, TreeMap<String, TreeMap<String, List<String>>>> complexObject = new TreeMap<String, TreeMap<String, TreeMap<String, List<String>>>>(); 
		
		String filter = request.getParameter("filter"); // filtrage de l arbre 
		filter = filter.toLowerCase();
		
		tbSpBoSRSectoDAO sectoDao = new tbSpBoSRSectoDAO();
		Session session = sectoDao.getSession();
		String strReq = sectoDao.QUERY_TREE_SECTO;
		Query req = session.createSQLQuery(session.getNamedQuery(strReq).getQueryString());

		req.setString("data", unite + periode);
		req.setInteger("cs_adm_pdt", cs_adm_pdt);
		req.setInteger("cs_adm_rgpt", cs_adm_rgpt);
		req.setInteger("cs_adm_prstn", cs_adm_prstn);
		req.setInteger("CS_SRC", CS_SRC);
		req.setInteger("cs_month", cs_month);
		req.setInteger("cs_network", cs_network);
		
		ArrayList result = new ArrayList(req.list());
		Iterator iter = result.iterator();
		HashMap hm = new HashMap();
		String libReseau = "";
		String iconReseau = "";
		while (iter.hasNext()) {
			Object[] tmp = (Object[]) iter.next();
			
			Double d_z = UtilsSalesReport.getDeltaPm(Double.parseDouble(tmp[10].toString()), Double.parseDouble(tmp[11].toString()), Double.parseDouble(tmp[12].toString()), Double.parseDouble(tmp[13].toString()), 1);
			Double d_r = UtilsSalesReport.getDeltaPm(Double.parseDouble(tmp[14].toString()), Double.parseDouble(tmp[15].toString()), Double.parseDouble(tmp[16].toString()), Double.parseDouble(tmp[17].toString()), 1);
			Double d_s = UtilsSalesReport.getDeltaPm(Double.parseDouble(tmp[18].toString()), Double.parseDouble(tmp[19].toString()), Double.parseDouble(tmp[20].toString()), Double.parseDouble(tmp[21].toString()), 1);
			Double d_u = UtilsSalesReport.getDeltaPm(Double.parseDouble(tmp[22].toString()), Double.parseDouble(tmp[23].toString()), Double.parseDouble(tmp[24].toString()), Double.parseDouble(tmp[25].toString()), 1);
			Double d_f = UtilsSalesReport.getDeltaPm(Double.parseDouble(tmp[26].toString()), Double.parseDouble(tmp[27].toString()), Double.parseDouble(tmp[28].toString()), Double.parseDouble(tmp[29].toString()), 1);
			
			libReseau = tmp[1].toString();
			iconReseau = ColorRenderer.icon(d_f);
			
			String libZone = tmp[2].toString() + ";" + tmp[3].toString() + ";" + ColorRenderer.icon(d_z);
			String libRegion = tmp[4].toString() + ";" + tmp[5].toString() + ";" + ColorRenderer.icon(d_r);
			String libSecteur = tmp[6].toString() + ";" + tmp[7].toString() + ";" + ColorRenderer.icon(d_s);
			String libUga = tmp[8].toString() + ";" + tmp[9].toString() + ";" + ColorRenderer.icon(d_u);
			
			if (libZone.toLowerCase().contains(filter)
					|| libRegion.toLowerCase().contains(filter)
					|| libSecteur.toLowerCase().contains(filter)
					|| libUga.toLowerCase().contains(filter)
					|| filter.equals("")) {

				if (complexObject.get(libZone) == null) {
					complexObject.put(libZone, new TreeMap<String, TreeMap<String, List<String>>>());
				}
				if (complexObject.get(libZone).get(libRegion) == null) {
					complexObject.get(libZone).put(libRegion, new TreeMap<String, List<String>>());
				}
				if (complexObject.get(libZone).get(libRegion).get(libSecteur) == null) {
					complexObject.get(libZone).get(libRegion).put(libSecteur, new ArrayList<String>());
				}
				if (!complexObject.get(libZone).get(libRegion).get(libSecteur).contains(libUga)) {
					complexObject.get(libZone).get(libRegion).get(libSecteur).add(libUga);
				}
			}
		}
		
		JSONArray jsonArrayZones = new JSONArray();
		
		for (Map.Entry<String, TreeMap<String, TreeMap<String, List<String>>>> entry : complexObject.entrySet()) {
			JSONObject jsonObjectZone = new JSONObject();    
			JSONObject dataZone = new JSONObject(); 
			JSONObject code = new JSONObject(); 
			code.put("id", entry.getKey().toString().split(";")[0] + "-Zone");
			dataZone.put("attr", code);
			dataZone.put("title", entry.getKey().toString().split(";")[1]);
			dataZone.put("icon", entry.getKey().toString().split(";")[2]);
			jsonObjectZone.put("data", dataZone);
			
			JSONArray jsonArrayRegions = new JSONArray();
			
			for (Map.Entry<String, TreeMap<String, List<String>>> r : entry.getValue().entrySet()) {
				JSONObject jsonObjectRegion = new JSONObject(); 
				JSONObject dataRegion = new JSONObject(); 
				code = new JSONObject(); 
				code.put("id", r.getKey().toString().split(";")[0] + "-Region");
				dataRegion.put("attr", code);
				dataRegion.put("title", r.getKey().toString().split(";")[1]);
				dataRegion.put("icon", r.getKey().toString().split(";")[2]);
				jsonObjectRegion.put("data", dataRegion);
				
				JSONArray jsonArraySect = new JSONArray();
				
				for (Map.Entry<String, List<String>> sect : r.getValue().entrySet()) {
					JSONObject jsonObjectSect = new JSONObject();  
					JSONObject dataSect = new JSONObject(); 
					code = new JSONObject(); 
					code.put("id", sect.getKey().toString().split(";")[0] + "-Secteur");
					dataSect.put("attr", code);
					dataSect.put("title", sect.getKey().toString().split(";")[1]);
					dataSect.put("icon", sect.getKey().toString().split(";")[2]);
					jsonObjectSect.put("data", dataSect);
					
					JSONArray jsonArrayUga = new JSONArray();
					
					for (String ug : sect.getValue()) {
						JSONObject jsonObjectUga = new JSONObject(); 
						JSONObject dataUga = new JSONObject(); 
						code = new JSONObject(); 
						code.put("id", ug.toString().split(";")[0] + "-UGA");
						dataUga.put("attr", code);
						dataUga.put("title", ug.toString().split(";")[1]);
						dataUga.put("icon", ug.toString().split(";")[2]);
						jsonObjectUga.put("data", dataUga);
						
						jsonArrayUga.add(jsonObjectUga);
					}
					
					jsonObjectSect.put("children", jsonArrayUga);
					
					jsonArraySect.add(jsonObjectSect);
				}
				
				jsonObjectRegion.put("children", jsonArraySect);
				
				jsonArrayRegions.add(jsonObjectRegion);
			}
			
			jsonObjectZone.put("children", jsonArrayRegions);
			
			jsonArrayZones.add(jsonObjectZone);
		}
		
		// Niveau France (racine principale)
		JSONObject jsonObjectFrance = new JSONObject();
		jsonObjectFrance.put("children", jsonArrayZones);
		
		JSONObject dataZone = new JSONObject(); 
		JSONObject code = new JSONObject(); 
		code.put("id", "France");
		dataZone.put("attr", code);
		dataZone.put("title", libReseau);
		dataZone.put("icon", iconReseau);
		jsonObjectFrance.put("data", dataZone);
		
		hm.put("datas", jsonObjectFrance);
		
		hm.put("niveau", (String) sessionObject.getAttribute("niveau"));
		
		hm.put("cs_niveau", (Integer) sessionObject.getAttribute("cs_niveau"));
		
		hm.put("libReseau", libReseau);
		
		JSONObject json = JSONObject.fromObject(hm);

		response.addHeader("Content-Type", "application/json");
        response.getOutputStream().write(json.toString().getBytes("UTF-8"));
        response.getOutputStream().flush();

		return null;
	}

}
